package com.smallcc.controller;

import com.smallcc.config.ProjectUrlConfig;
import com.smallcc.constant.CookieConstant;
import com.smallcc.constant.RedisConstant;
import com.smallcc.dataobject.SellerInfo;
import com.smallcc.enums.ResultEnum;
import com.smallcc.service.SellerService;
import com.smallcc.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 晓风过境
 * @TODO    卖家用户Controller
 * @date 2018/4/2 15:20
 * @day 02
 * @return $text$
 * @title ${CLASS_NAME}
 * @project_name sell
 */
@Controller
@RequestMapping("/seller")
public class SellerUserController {
    @Autowired
    private SellerService sellerService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid, HttpServletResponse response, Map<String,Object> map){
        SellerInfo sellerInfo = sellerService.findSellerInfoByOpenid(openid);
        //openid去数据库匹配
        if(sellerInfo==null){
        map.put("msg", ResultEnum.LOGIN_FAIL.getMessage());
        map.put("url","/sell/seller/order/list");
        }
        //设置token到redis
        String token= UUID.randomUUID().toString();
        Integer expire= RedisConstant.EXPIRE;

        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX,token),openid,expire, TimeUnit.SECONDS);
        //设置token到cookie
        CookieUtil.setCookie(response, CookieConstant.TOKEN,token,expire);
        return new ModelAndView("redirect:"+projectUrlConfig.getSell()+"/sell/seller/order/list");

    }
    @PostMapping("/logout")
    public ModelAndView logout(HttpServletRequest request,Map<String,Object> map,
                        HttpServletResponse response ){
        //从Cookie中查询
        Cookie cookie=CookieUtil.getCookie(request,CookieConstant.TOKEN);
        if(cookie!=null){
        //清除redis
            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
            //清除Cookie
            CookieUtil.setCookie(response,CookieConstant.TOKEN,null,0);
        }
        map.put("msg", ResultEnum.LOGOUT_SUCCESS.getMessage());
        map.put("url", "/sell/seller/order/list");
        return new ModelAndView("common/success", map);

    }
}
